package com.msb.mall.controller;

import com.alibaba.fastjson.JSON;
import com.msb.common.constant.AuthConstant;
import com.msb.common.utils.HttpUtils;
import com.msb.common.utils.R;
import com.msb.common.vo.MemberVO;
import com.msb.mall.feign.MemberFeignService;
import com.msb.mall.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhangjiajun
 * @Email zhangjiajun@hydsoft.com
 * @Description
 * @Date 2025/8/2 15:42
 */
@Controller
public class OAuth2Controller {


    @Autowired
    MemberFeignService memberFeignService;


    /**
     * 微博登录成功  回调地址   --通过code获取token
     * <p>
     * https://api.weibo.com
     * /oauth2/access_token?
     * client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
     *
     * @param code
     * @return
     */
    @GetMapping("/oauth/weibo/success")
    public String weiboOAuth(@RequestParam("code") String code, HttpSession session) throws Exception {
        //根据code获取token信息
        Map<String, String> body = new HashMap<>();
        body.put("client_id", "client_id");
        body.put("client_secret", "client_secret");
        body.put("grant_type", "authorization_code");
        body.put("redirect_uri", "http://auth.msb.com//oauth/weibo/success");
        body.put("code", code);

        HttpResponse response = HttpUtils.doPost("https://api.weibo.com",
                "/oauth2/access_token",
                "post",
                new HashMap<>(),
                null,
                body);

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            //获取token失败,就跳到登录页面
            return "redirect:http://auth.msb.com/login.html";
        }

        //获取token成功
        String json = EntityUtils.toString(response.getEntity());
        SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

        R r = memberFeignService.socialLogin(socialUser);
        if (r.getCode() != 0) {
            //登录错误
            return "redirect:http://auth.msb.com/login.html";
        }
        String entityJson = (String) r.get("entity");
        MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
        session.setAttribute(AuthConstant.AUTH_SESSION_REDIS, memberVO);

        //注册成功跳转到商城的首页
        return "redirect:http://mall.msb.com/home";
    }
}
